package service;

import bean.Category;
import dao.util.CategoryCreate;
import mapper.CategoryMapper;

import java.util.List;
import java.util.Map;

public class CategoryService {
    private final CategoryCreate create = new CategoryCreate();

    public List<Category> listByUserId(Integer userId) {
        CategoryMapper mapper = create.getMapperClass();
        List<Category> list = mapper.selectByUserId(userId);
        create.closeSession();
        return list;
    }

    public Category getById(Integer id) {
        CategoryMapper mapper = create.getMapperClass();
        Category c = mapper.selectById(id);
        create.closeSession();
        return c;
    }

    public int add(Category category) {
        CategoryMapper mapper = create.getMapperClass();
        int r = mapper.insertCategory(category);
        create.commit();
        create.closeSession();
        return r;
    }

    public int update(Category category) {
        CategoryMapper mapper = create.getMapperClass();
        int r = mapper.updateCategory(category);
        create.commit();
        create.closeSession();
        return r;
    }

    public int delete(Integer id, Integer userId) {
        CategoryMapper mapper = create.getMapperClass();
        Category c = new Category();
        c.setId(id);
        c.setUserId(userId);
        int r = mapper.deleteCategory(c);
        create.commit();
        create.closeSession();
        return r;
    }

    public boolean existsByName(Integer userId, String name, Integer excludeId) {
        CategoryMapper mapper = create.getMapperClass();
        int count = mapper.existsByName(userId, name, excludeId);
        create.closeSession();
        return count > 0;
    }

    public int countNotesByCategory(Integer categoryId) {
        CategoryMapper mapper = create.getMapperClass();
        int c = mapper.countNotesByCategory(categoryId);
        create.closeSession();
        return c;
    }

    public List<Map<String, Object>> categoriesWithNoteCount(Integer userId) {
        CategoryMapper mapper = create.getMapperClass();
        List<Map<String, Object>> list = mapper.selectCategoriesWithNoteCount(userId);
        create.closeSession();
        return list;
    }
}